package flyshoes.interceptors;

import flyshoes.utils.ThreadLocalUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//此拦截器获取来自网关的userinfo并把它存入ThreadLocalUtil当中
@Component
@ConditionalOnClass(DispatcherServlet.class)
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 测试用：打印请求URI
//        String requestURI = request.getRequestURI();
//        System.out.println("拦截请求: " + requestURI);
        //1.获取登录用户信息
        String userInfo = request.getHeader("user-info");
        //2.判断是否获取了用户，如果有，存入Thread Local
        if (userInfo != null && !userInfo.equals("")) {
            Integer userId = Integer.parseInt(userInfo);
            ThreadLocalUtil.set(userId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
